#!/usr/bin/php
<?php
/*
 * $Header$
 */

// We need Zend for the Google API, Getopt, and Config.
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Photos');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Console_Getopt');
Zend_Loader::loadClass('Zend_Config_Ini');

// Get CLI options
try {
    $opts = new Zend_Console_Getopt(
        array(
            'photo_dir=s' => 'Directory containing the pics to be uploaded (REQUIRED)',
            'config=s'  => 'config path option',
            'album=s'   => 'Picasa album name [default]',
            'username|u=w' => 'Picasa (Google) username/email',
            'password|p=w' => 'Picasa (Google) password',
            'tags=s' => 'comma delimited list of tags to apply to the pics',
            'gallery' => 'this is a gallery album.  Copy it'
        ));
    $opts->parse();
    if (empty($opts->photo_dir)) {
        throw new Zend_Console_Getopt_Exception("** --photo_dir is a required option. **\n",$opts->getUsageMessage());
    }
} catch (Zend_Console_Getopt_Exception $e) {
    echo $e->getMessage();
    echo $e->getUsageMessage();
    exit;
}

// Suck in the config
// Add exception handling here.
if (isset($opts->config)) {
    $config = new Zend_Config_Ini($opts->config);
} else if ($homedir = getenv("HOME")) {
    $config = new Zend_Config_Ini($homedir .'/.upload2picasa.ini');
} else {
    $config = new Zend_Config_Ini(dirname(__FILE__) .'/upload2picasa.ini');
}

$serviceName = Zend_Gdata_Photos::AUTH_SERVICE_NAME;

// Set $username
$username = null;
if (isset($config->picasa->username)) {
    $username = $config->picasa->username;
}
if (isset($opts->username)) {
    $username = $opts->username;
}

// Set $pass
$pass = null;
if (isset($config->picasa->password)) {
    $pass = $config->picasa->password;
}
if (isset($opts->password)) {
    $pass = $opts->password;
}

try {
    $client = Zend_Gdata_ClientLogin::getHttpClient($username, $pass, $serviceName);
} catch (Zend_Gdata_App_AuthException $e) {
    echo "Fatal Error:\n\t" . $e->getMessage() . "\n";
    exit;
}

// update the second argument to be CompanyName-ProductName-Version
$gp = new Zend_Gdata_Photos($client, "upload2picasa");

if (isset($opts->gallery) && $opts->gallery === true) {
    echo 'gallery';
    migrate_gallery($opts->photo_dir);
} else {
    upload_photos($opts->photo_dir);
}

function upload_photos($photo_dir,$tags=null) {
    global $gp;
    $photo_list = get_photo_list($photo_dir);

    // Pull a list of what is already in the dropbox
    $in_dropbox = array();
    try {
        $query = $gp->newAlbumQuery();

        $query->setAlbumName("DropBox");

        $albumFeed = $gp->getAlbumFeed($query);
        foreach ($albumFeed as $albumEntry) {
            $in_dropbox[] = $albumEntry->title->text;
        }
    } catch (Zend_Gdata_App_HttpException $e) {
        print "Drop Box album is currently empty.\n";
    }

    foreach($photo_list as $photo) {
        if (in_array($photo,$in_dropbox)) {
            print "$photo has already been uploaded.\n";
            continue;
        }
        print "Processing $photo.\n";
        $exif = exif_read_data($photo_dir ."/". $photo);
        if (isset($exif['DateTimeOriginal'])) {
            list($year,$rest) = explode(':',$exif['DateTimeOriginal'],2);
            $photoTags = $year;
        } else {
            $photoTags = '';
        }

        $filename = $photo_dir ."/". $photo;
        $photoName = $photo;
        if (isset($opts->tags)) {
            $photoTags .= ','.$opts->tags;
        }

        // We use the albumId of 'default' to indicate that we'd like to upload
        // this photo into the 'drop box'.  This drop box album is automatically 
        // created if it does not already exist.
        $albumId = isset($opts->album) ? $opts->album : "default";

        $fd = $gp->newMediaFileSource($filename);
        $fd->setContentType("image/jpeg");

        // Create a PhotoEntry
        $photoEntry = $gp->newPhotoEntry();

        $photoEntry->setMediaSource($fd);
        $photoEntry->setTitle($gp->newTitle($photoName));
        //$photoEntry->setSummary($gp->newSummary($photoCaption));
        
        if (!empty($photoTags)) {
            // add some tags
            $keywords = new Zend_Gdata_Media_Extension_MediaKeywords();
            $keywords->setText($photoTags);
            $photoEntry->mediaGroup = new Zend_Gdata_Media_Extension_MediaGroup();
            $photoEntry->mediaGroup->keywords = $keywords;
        }

        // We use the AlbumQuery class to generate the URL for the album
        $albumQuery = $gp->newAlbumQuery();

        $albumQuery->setAlbumId($albumId);

        print "Uploading $photo.\n";
        // We insert the photo, and the server returns the entry representing
        // that photo after it is uploaded
        $insertedEntry = $gp->insertPhotoEntry($photoEntry, $albumQuery->getQueryUrl());
    }
}

function get_photo_list($photo_dir=null) {
    $photos = array();
    if ($handle = opendir($photo_dir)) {
        while (false !== ($file = readdir($handle))) {
            if (preg_match('/\.jpg$/i',$file)) {
                $photos[] = $file;
            }
        }
        closedir($handle);
    } else {
        print "Unable to read $photo_dir contents.\n";
        exit;
    }
    return $photos;
}

function migrate_gallery($photo_dir=null) {
    global $gp,$config;
    
    $db = Zend_Db::factory($config->gallery->database);
    $db->setFetchMode(Zend_Db::FETCH_OBJ);

    $table = array(
        'g2_Item'               => array('item' => 'g2_Item'),
        'g2_FileSystemEntity'   => array('fs' => 'g2_FileSystemEntity'),
        'g2_ItemAttributesMap'  => array('attr' => 'g2_ItemAttributesMap')
    );

    // Extract the path to the album dir beyond the base path
    preg_match("@^$base(.+)$@",$path,$matches);
    $album_path = explode('/',$matches[1]);

    // Now gotta search for the item ids for the path.  Note that item names
    // can be duplicates.


    $select_album = $db->select()
        ->from(
}
?>
